﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

namespace AdministrationWeb
{
    public partial class StudentUsageReport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (tbxEnd.Text == "")
            {
                tbxEnd.Text = DateTime.Now.ToString("MM/dd/yyyy");
            }
            int ddl = Convert.ToInt32(ddlGroupby.SelectedValue);
          if(Page.IsPostBack)
           {
             if (ddl == 1)
             {
                 RequiredFieldValidatorYear.Enabled = false;
                 RangeValidatorYear.Enabled = false;
                lblYear.Enabled = false;
                lblYear.Visible = false;
                tbxYear.Enabled = false;
                tbxYear.Visible = false;

                lblUserId.Enabled = false;
                lblUserId.Visible = false;
                tbxUserId.Enabled = false;
                tbxUserId.Visible = false;

                lblActionType.Enabled = false;
                lblActionType.Visible = false;
                ddlActionType.Enabled = false;
                ddlActionType.Visible = false;
            }
            else if (ddl == 2)
            {
                RequiredFieldValidatorYear.Enabled = true;
                RangeValidatorYear.Enabled = true;
                lblYear.Enabled = true;
                lblYear.Visible = true;
                tbxYear.Enabled = true;
                tbxYear.Visible = true;

                lblUserId.Enabled = false;
                lblUserId.Visible = false;
                tbxUserId.Enabled = false;
                tbxUserId.Visible = false;

                lblActionType.Enabled = false;
                lblActionType.Visible = false;
                ddlActionType.Enabled = false;
                ddlActionType.Visible = false;
            }
            else
             {
                 RequiredFieldValidatorYear.Enabled = false;
                 RangeValidatorYear.Enabled = false;
                 lblYear.Enabled = false;
                 lblYear.Visible = false;
                 tbxYear.Enabled = false;
                 tbxYear.Visible = false;

                 lblUserId.Enabled = true;
                 lblUserId.Visible = true;
                 tbxUserId.Enabled = true;
                 tbxUserId.Visible = true;

                 lblActionType.Enabled = true;
                 lblActionType.Visible = true;
                 ddlActionType.Enabled = true;
                 ddlActionType.Visible = true;
             }
          }
        }

        protected void btnRun_Click(object sender, EventArgs e)
        {
                if (Page.IsValid)
                {
             /*     ddlGrouBy =
             * 1    GET_ALL_STUDENT_ACTIVITY requires dates
             * 2    GET_STUDENT_YEAR_ACTIVITY requires dates and year
             * 3    GET_STUDENT_MENTOR_ACTIVITY requires userId, actionType and dates
             * 4    GET_STUDENT_PATHWAY_ACTIVITY requires userId, actionType and dates
             * 5    GET_STUDENT_FOCUS_ACTIVITY requires userId, actionType and dates
             * 
             * thought process. See what ddl is and allow fields to be editable
             */
                    StudentReport sr = new StudentReport();
                    int ddlValue = Convert.ToInt32(ddlGroupby.SelectedValue);
                    DateTime endDate = Convert.ToDateTime(tbxEnd.Text);
                    var endOfDay = new TimeSpan(23, 59, 59);
                    endDate = endDate.Date + endOfDay;
                    DateTime startDate = Convert.ToDateTime(tbxStart.Text);
                    String endDateString = String.Format("{0:yyyy-MM-dd}", endDate);
                    String startDateString = String.Format("{0:yyyy-MM-dd}", startDate);
                    GridViewReports.Visible = true;
                    switch (ddlValue)
                    {
                        case 1:
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = formatSQl(sr.getAllStudentActivitySQL(), startDate, endDate);
                            break;
                        case 2:
                            if (string.Equals(tbxYear.Text, "")) break;
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = formatSQl(sr.getStudentYearActivitySQL(), startDate, endDate);
                            SqlDataSource1.SelectParameters.Add("?gradYear", tbxYear.Text);
                            break;
                        case 3:
                            if (String.Equals("",ddlActionType.SelectedValue) || String.Equals(tbxUserId.Text,"")) break;
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = formatSQl(sr.getStudentMentorActivitySQL(), startDate, endDate);
                            SqlDataSource1.SelectParameters.Add("?userId", tbxUserId.Text);
                            SqlDataSource1.SelectParameters.Add("?actionType", ddlActionType.SelectedValue);       
                            
                            break;
                        case 4:
                            if (String.Equals("", ddlActionType.SelectedValue) || String.Equals(tbxUserId.Text, "")) break;
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = formatSQl(sr.getStudentPathwayActivitySQL(), startDate, endDate);
                            SqlDataSource1.SelectParameters.Add("?userId", tbxUserId.Text);
                            SqlDataSource1.SelectParameters.Add("?actionType", ddlActionType.SelectedValue);       
                            break;
                        case 5:
                            if (String.Equals("", ddlActionType.SelectedValue) || String.Equals(tbxUserId.Text, "")) break;
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = formatSQl(sr.getStudentFocusActivitySQL(), startDate, endDate);
                            SqlDataSource1.SelectParameters.Add("?userId", tbxUserId.Text);
                            SqlDataSource1.SelectParameters.Add("?actionType", ddlActionType.SelectedValue);       
                            break;
                        default:
                            SqlDataSource1.SelectParameters.Clear();
                            SqlDataSource1.SelectCommand = "SELECT * FROM mentor LIMIT 0";
                            break;
                    }
                }
            
        }

        private string formatSQl(string sql, DateTime startDate, DateTime endDate)
        {
            //format dates
            string startDateString = "\"" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", startDate) + "\"";
            string endDateString = "\"" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", endDate) + "\"";
            string temp1, temp2;
            temp1 = sql.Replace("@minDate", startDateString);
            temp2 = temp1.Replace("@maxDate", endDateString);
            return temp2;
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                DateTime currentDate = DateTime.Now;
                String date = String.Format("{0:mm-dd-yyyy}", currentDate);

                String sFileName;
                sFileName = "RecordsChangedReport" + date + ".csv";

                //clear response
                HttpContext.Current.Response.Clear();

                //add http header for the content type to tell browser to associate file with excel
                HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sFileName));

                HttpContext.Current.Response.ContentType = "application/ms-excel";

                System.Text.StringBuilder sbCsvValues = new System.Text.StringBuilder();

                //this will need to change based on selection
                for (int i = 0; i < GridViewReports.HeaderRow.Cells.Count; i++)
                {
                    sbCsvValues.Append(escapeFields(GridViewReports.HeaderRow.Cells[i].Text));
                }
                sbCsvValues.Append("\n");

                for (int j = 0; j < GridViewReports.Rows.Count; j++)
                {
                    for (int k = 0; k < GridViewReports.Rows[j].Cells.Count; k++)
                    {
                        //separating gridview columns with comma
                        sbCsvValues.Append(escapeFields(GridViewReports.Rows[j].Cells[k].Text));
                        sbCsvValues.Append(",");
                    }
                    //appending new line for gridview rows
                    sbCsvValues.Append("\n");
                }

                // write the response to the HTTP stream back to the client browser.
                HttpContext.Current.Response.Write(sbCsvValues.ToString());

                // End the stream write and commit it.
                HttpContext.Current.Response.End();
            }
        }

        private string escapeFields(string fieldToEscape)
        {
            if (fieldToEscape.Contains(","))
            {
                if (fieldToEscape.Contains("\""))
                {
                    return "\"" + fieldToEscape.Replace("\"", "\"\"") + "\"";
                }
                else
                {
                    return "\"" + fieldToEscape + "\"";
                }
            }
            else
            {
                return fieldToEscape;
            }
        }

    }
}